package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.CheckingService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.StringUtils;
import com.lt.test.entity.DTO.*;
import com.lt.test.entity.QueryModel.CheckingQueryModel;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.provider.mapper.CheckingMapper;
import com.lt.test.provider.mapper.SPLOrderMapper;
import com.lt.test.provider.mapper.UserMapper;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhengchuan on 2017/4/21.
 */
@Service(version = "1.0.0")
public class CheckingServiceImpl implements CheckingService {
    private static final Logger logger = LoggerFactory.getLogger(CheckingServiceImpl.class);

    @Resource
    private CheckingMapper checkingMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SPLOrderMapper splOrderMapper;

    @Override
    public PageDTO<GeneralLedgerDTO> getGeneralLedgerByPageQuery(CheckingQueryModel checkingQueryModel) throws CustomException {
        Integer pageSize = checkingQueryModel.getPageSize() == null ? 10 : checkingQueryModel.getPageSize();
        Integer page = checkingQueryModel.getPage() == null ? 1 : checkingQueryModel.getPage();
        Long beginNum = (long) ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        PageQueryModel pageQueryModel = new PageQueryModel();
        pageQueryModel.setBeginNum(beginNum);
        pageQueryModel.setEndNum(endNum);

        List<PageFilter> filters = generatePageFilter(checkingQueryModel);

        pageQueryModel.setFilters(filters);
        List<GeneralLedgerDTO> generalLedgerList = null;
        try {
            generalLedgerList = checkingMapper.getGeneralLedgerByPageQuery(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取总账数据失败");
        }
        int recordCount = 0;
        try {
            recordCount = checkingMapper.getGeneralLedgerCountByPageQuery(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取总账总数失败");
        }
        PageDTO<GeneralLedgerDTO> result = new PageDTO<>(page, pageSize, generalLedgerList, recordCount);
        return result;
    }


    @Override
    public Map<String, Object> getTbcocompNamesAndBankNamesAndMerNames(String userId) throws CustomException {
        System.out.println("========getTbcocompNamesAndBankNamesAndMerNames=====>"+userId);
        CustomUser customUser = null;
        try {
            customUser = userMapper.findCustomUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> params = new HashMap<>();
        if (customUser != null) {
            params.put("tbcocompId",customUser.getTbcocompId());
            params.put("bankCode",customUser.getBankCode());

        }
        Map<String, Object> result = new HashedMap(3);
        try {
            List<String> tbcocompNames = checkingMapper.getTbcocompNames(params);
            result.put("tbcocompNames", tbcocompNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            List<String> bankNames = checkingMapper.getBankNames(params);
            result.put("bankNames", bankNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            List<String> merNames = checkingMapper.getMerNames(params);
            result.put("merNames", merNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public PageDTO<CheckingDetailDTO> getCheckingDetailByPageQuery(CheckingQueryModel checkingQueryModel) throws CustomException {
        System.out.println("============> "+checkingQueryModel.getUserId());
        Integer pageSize = checkingQueryModel.getPageSize() == null ? 10: checkingQueryModel.getPageSize();
        Integer page = checkingQueryModel.getPage() == null ? 1 : checkingQueryModel.getPage();
        Long beginNum = (long) ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        PageQueryModel pageQueryModel = new PageQueryModel();
        pageQueryModel.setBeginNum(beginNum);
        pageQueryModel.setEndNum(endNum);

        List<PageFilter> filters = generatePageFilter(checkingQueryModel);


        pageQueryModel.setFilters(filters);
        List<CheckingDetailDTO> generalLedgerList = null;
        try {
            generalLedgerList = checkingMapper.getCheckingDetailByPageQuery(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取明细数据失败");
        }
        int recordCount = 0;
        try {
            recordCount = checkingMapper.getCheckingDetailCountByPageQuery(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取明细总数失败");
        }
        PageDTO<CheckingDetailDTO> result = new PageDTO<>(page, pageSize, generalLedgerList, recordCount);
        return result;
    }

    @Override
    public List<Map<String, Object>> getGeneralLedgerToExportExcel(CheckingQueryModel checkingQueryModel) throws CustomException {
        List<PageFilter> filters = generatePageFilter(checkingQueryModel);
        PageQueryModel pageQueryModel = new PageQueryModel();

        pageQueryModel.setFilters(filters);
        List<Map<String, Object>> generalLedgerList = null;
        try {
            generalLedgerList = checkingMapper.getGeneralLedgerToExportExcel(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取总账数据用于导出Excel失败");
        }
        return generalLedgerList;
    }

    @Override
    public List<Map<String, Object>> getDetailToExportExcel(CheckingQueryModel checkingQueryModel) throws CustomException {
        List<PageFilter> filters = generatePageFilter(checkingQueryModel);
        PageQueryModel pageQueryModel = new PageQueryModel();
        pageQueryModel.setFilters(filters);
        List<Map<String, Object>> generalLedgerList = null;
        try {
            generalLedgerList = checkingMapper.getDetailToExportExcel(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取明细账数据用于导出Excel失败");
        }
        return generalLedgerList;
    }

    private List<PageFilter> generatePageFilter(CheckingQueryModel checkingQueryModel) throws CustomException {
        List<PageFilter> filters = new ArrayList<>(10);

        CustomUser customUser = null;
        try {
            customUser = userMapper.findCustomUserById(checkingQueryModel.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询用户角色失败");
        }

        if (customUser != null) {
            if (customUser.getTbcocompId() != null && !customUser.getTbcocompId().equals("")) {
                PageFilter pageFilter = new PageFilter();
                pageFilter.setFilterName("a.TBCOCOMPID");
                pageFilter.setFilterType("=");
                pageFilter.setFilterValue("'" + customUser.getTbcocompId() + "'");
                filters.add(pageFilter);
            }
            if (customUser.getBankCode() != null && !customUser.getBankCode().equals("")) {
                PageFilter pageFilter = new PageFilter();
                pageFilter.setFilterName("a.BANKCODE");
                pageFilter.setFilterType("=");
                pageFilter.setFilterValue("'" + customUser.getBankCode() + "'");
                filters.add(pageFilter);
            }
        }
        if (checkingQueryModel.getTbcocompName() != null && !checkingQueryModel.getTbcocompName().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.TBCOCOMPNAME");
            pageFilter.setFilterType("=");
            pageFilter.setFilterValue("'" + checkingQueryModel.getTbcocompName() + "'");
            filters.add(pageFilter);
        }
        if (checkingQueryModel.getBankName() != null && !checkingQueryModel.getBankName().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.BANKNAME");
            pageFilter.setFilterType("=");
            pageFilter.setFilterValue("'" + checkingQueryModel.getBankName() + "'");
            filters.add(pageFilter);
        }
        if (checkingQueryModel.getMerName() != null && !checkingQueryModel.getMerName().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.mername");
            pageFilter.setFilterType("=");
            pageFilter.setFilterValue("'" + checkingQueryModel.getMerName() + "'");
            filters.add(pageFilter);
        }
        if (checkingQueryModel.getSettleDate() != null && !checkingQueryModel.getSettleDate().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.SETTLEDATE");
            pageFilter.setFilterType("LIKE");
            pageFilter.setFilterValue("'%" + checkingQueryModel.getSettleDate() + "%'");
            filters.add(pageFilter);
        }
        if (checkingQueryModel.getPayType() != null && !checkingQueryModel.getPayType().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.pay_type");
            pageFilter.setFilterType("=");
            pageFilter.setFilterValue(checkingQueryModel.getPayType());
            filters.add(pageFilter);
        }
        if (checkingQueryModel.getOrderId() != null && !checkingQueryModel.getOrderId().equals("")) {
            PageFilter pageFilter = new PageFilter();
            pageFilter.setFilterName("a.pay_orderid");
            pageFilter.setFilterType("=");
            pageFilter.setFilterValue("'" + checkingQueryModel.getOrderId() + "'");
            filters.add(pageFilter);
        }
        return filters;
    }

    @Override
    public List<Map<String, Object>> selectEmpNameToSelected(Map<String, String> params) throws CustomException {


        try {
            return checkingMapper.selectEmpNameToSelected(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询所有客户经理名称失败");
        }
    }

    @Override
    public List<Map<String, Object>> selectChannelNameToSelected(Map<String, String> params) throws CustomException {

        try {
            return checkingMapper.selectChannelNameToSelected(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询所有机构名称失败");
        }
    }

    @Override
    public List<Map<String, Object>> selectMaterialCompanyToSelected() {
        return checkingMapper.selectMaterialCompanyToSelected();
    }

    @Override
    public List<Map<String, Object>> selectQuXianNameToSelected(Map<String, String> params) throws CustomException {

        String quXianName = params.get("quXianName");
        if (quXianName != null && !quXianName.equals("")) {
            String channelId = null;
            try {
                channelId = splOrderMapper.getIdByChannleName(quXianName);

            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取区县失败");
            }
            params.put("parentChannelId", channelId);
            logger.info("区县查询 channelId : " + channelId);
        }
        try {
            return checkingMapper.selectQuXianNameToSelected(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询所有区县名称失败");
        }
    }

    @Override
    public PageDTO<SmokeCustomerListDTO> getSmokeCustomerByPageQuery(Map<String, String> stringMap) throws CustomException {
        Integer pageSize = 10;
        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));
        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum", beginNum.toString());
        stringMap.put("endNum", endNum.toString());

        List<SmokeCustomerListDTO> smokeCustomerList = null;
        try {
            smokeCustomerList = checkingMapper.getSmokeCustomerByPageQuery(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取卷烟记录数据失败");
        }
        int recordCount = 0;
        try {
            recordCount = checkingMapper.getSmokeCustomerCountByPageQuery(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取卷烟记录总数失败");
        }
        PageDTO<SmokeCustomerListDTO> result = new PageDTO<>(page.intValue(), pageSize, smokeCustomerList, recordCount);
        return result;
    }
    @Override
    public PageDTO<Map<String,String>> getSmokeCustomerStatisticsListByPageQuery(Map<String, String> stringMap) throws CustomException {
        Integer pageSize = 10;
        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));
        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum", beginNum.toString());
        stringMap.put("endNum", endNum.toString());

        List<Map<String,String>> smokeCustomerList = null;
        try {
            smokeCustomerList = checkingMapper.getSmokeCustomerStatisticsListByPageQuery(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取卷烟记录数据失败");
        }
        int recordCount = 0;
        try {
            recordCount = checkingMapper.getSmokeCustomerCountStatisticsListByPageQuery(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取卷烟记录总数失败");
        }
        PageDTO<Map<String,String>> result = new PageDTO<>(page.intValue(), pageSize, smokeCustomerList, recordCount);

        return result;
    }

    @Override
    public List<Map<String, Object>> getSmokeCustomerByQuery(Map<String, String> params) throws CustomException {

        try {
            return checkingMapper.getSmokeCustomerByQuery(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取卷烟消费记录失败");
        }
    }

    @Override
    public List<Map<String, Object>> getMain1Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain1Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：不同时间段");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getCustomerMain1Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain1Data(stringMap);
    }

    @Override
    public List<Map<String, Object>> getCustomerMain2Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain2Data(stringMap);
    }
    @Override
    public List<Map<String, Object>> getCustomerMain3Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain3Data(stringMap);
    }
    @Override
    public List<Map<String, Object>> getCustomerMain4Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain4Data(stringMap);
    }
    @Override
    public List<Map<String, Object>> getCustomerMain5Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain5Data(stringMap);
    }    @Override
    public List<Map<String, Object>> getCustomerMain6Data(Map<String, String> stringMap) {
        return checkingMapper.getCustomerMain6Data(stringMap);
    }

    @Override
    public String getCustomerRegisterNum(Map<String, String> stringMap) {
        return checkingMapper.getCustomerRegisterNum(stringMap);
    }

    @Override
    public String getCustomerDayOrderNum(Map<String, String> stringMap) throws ParseException {
        //日均销售量
        String time = stringMap.get("time");
        if (StringUtils.isNullOrTrimEmpty(time) || time.length() != 7) {
            return null;
        }
        time += "-01";

        String orderNum = checkingMapper.getCustomerDayOrderNum(stringMap);

        if (StringUtils.isNullOrTrimEmpty(orderNum)) {
            return null;
        }

        Calendar now = Calendar.getInstance();
        now.setTime(new Date());

        Calendar timeC = Calendar.getInstance();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        timeC.setTime(simpleDateFormat.parse(time));

        int day = timeC.getActualMaximum(Calendar.DAY_OF_MONTH);
        if (now.get(Calendar.YEAR) == timeC.get(Calendar.YEAR) && now.get(Calendar.MONTH) == timeC.get(Calendar.MONTH))
        {
            day = now.get(Calendar.DATE);
        }
        Float orderN = Float.valueOf(orderNum);
        DecimalFormat decimalFormat = new DecimalFormat("0.0");

        return decimalFormat.format(orderN/day);
    }

    @Override
    public List<Map<String, Object>> getMain2Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain2Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：一次购买数量人次");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getMain3Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain3Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：业态分布购买人次数量");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getMain4Data(Map<String, String> stringMap) throws CustomException {
        try {
            List<Map<String,Object>> result = checkingMapper.getMain4Data(stringMap);
            logger.info("Main4Data is : "  + result.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：年龄购买分布");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getMain5Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain5Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：购买变化次数");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getMain6Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain6Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：消费者注册数");
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getMain7Data(Map<String, String> stringMap) throws CustomException {
        try {
            return checkingMapper.getMain7Data(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取卷烟统计数据失败：购买次数top10");
        }
        return null;
    }


    @Override
    public List<Map<String, String>> getBuyShopInfoByPhone(String phone) throws Exception {
        return checkingMapper.getBuyShopInfoByPhone(phone);
    }

    @Override
    public List<Map<String, Object>> selectOrderLevelToSelected() throws Exception {
        return checkingMapper.selectOrderLevelToSelected();
    }

    @Override
    public List<Map<String, Object>> selectBaseTypeNameToSelected() throws Exception {
        return checkingMapper.selectBaseTypeNameToSelected();
    }

    @Override
    public List<Map<String, Object>> selectCityTypeToSelected() throws Exception {
        return checkingMapper.selectCityTypeToSelected();
    }

    @Override
    public List<Map<String, Object>> getCustomerShop(Map<String, String> stringMap) {
        return checkingMapper.getCustomerShop(stringMap);
    }

    @Override
    public List<Map<String, Object>> getCarLastLocation(Map<String, String> stringMap) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        stringMap.put("deliveryTime", simpleDateFormat.format(new Date()));

        return checkingMapper.getCarLastLocation(stringMap);
    }
}
